<template>
  <div class="firstScreen">
    <el-card>
      <el-button
        @click="dialogVisible = true"
        icon="el-icon-circle-plus-outline"
        class="btn"
        plain
        >新增开屏页</el-button
      >
    </el-card>
    <el-table :data="tableData" styleid="width: 100%">
      <el-table-column prop="id" label="序号"> </el-table-column>
      <el-table-column prop="resource" label="开屏页">
        <template slot-scope="scope">
          <el-image
            class="img"
            style="width: 150px; height: 250px"
            :src="scope.row.resource"
            :preview-src-list="[scope.row.resource]"
          >
          </el-image>
        </template>
      </el-table-column>
      <el-table-column prop="online_date" label="上架时间"> </el-table-column>
      <el-table-column prop="offline_date" label="下架时间"> </el-table-column>
      <el-table-column label="管理">
        <template slot-scope="scope">
          <el-button
            type="success"
            size="small"
            @click="upOrDown(scope.row.id, 1)"
            plain
            >手动上架</el-button
          >
          <el-button
            type="info"
            size="small"
            @click="upOrDown(scope.row.id, 10)"
            plain
            >手动下架</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="page"
      :limit.sync="pageSize"
      @pagination="getList"
    />
    <el-dialog
      title="添加开屏页"
      :visible.sync="dialogVisible"
      @close="close"
      width="30%"
    >
      <el-form
        ref="form"
        :model="form"
        :rules="rules"
        label-width="80px"
        label-position="left"
      >
        <!-- <el-form-item label="序号" prop="id">
          <el-input
            @change="inputChange"
            style="width: 90%"
            v-model="form.id"
          ></el-input>
        </el-form-item> -->
        <el-form-item label="上架时间" prop="online_date">
          <el-date-picker
            v-model="form.online_date"
            type="date"
            placeholder="选择日期"
            format="yyyy-MM-dd"
            value-format="yyyy-MM-dd"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="下架时间" prop="offline_time">
          <el-date-picker
            v-model="form.offline_time"
            type="date"
            placeholder="选择日期"
            format="yyyy-MM-dd"
            value-format="yyyy-MM-dd"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="投放图片" prop="resource">
          <el-upload
            class="avatar-uploader"
            :http-request="upLoad"
            :on-preview="handlePictureCardPreview"
            :on-success="handleAvatarSuccess"
            :show-file-list="false"
            action
          >
            <img
              v-if="form.dialogImageUrl"
              :src="form.dialogImageUrl"
              class="avatar"
              style="width: 250px; height: 400px"
            />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer" style="text-align: center">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submit">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import Pagination from "@/components/Pagination"; // 分页
import {
  screenList,
  screenAdd,
  screenSetScreenStatus,
} from "@/api/operationManagement";
import { client } from "@/utils/oss.js";
import { ossToken } from "@/api/NotificationManagement";
export default {
  components: { Pagination },
  data() {
    return {
      dialogVisible: false,
      tableData: [],
      total: 1,
      page: 1,
      pageSize: 10,
      form: {
        // id: "",
        resource: "",
        online_date: "",
        offline_time: "",
        dialogImageUrl: "",
      },
      rules: {
        // id: [{ required: true, message: "请输ID", trigger: "blur" }],
        online_date: [
          { required: true, message: "请选择上架时间", trigger: "change" },
        ],
        offline_time: [
          { required: true, message: "请选择下架时间", trigger: "change" },
        ],
        resource: [
          { required: true, message: "请上传图片", trigger: "change" },
        ],
      },
    };
  },
  methods: {
    inputChange(value) {
      let bol = this.tableData.some((item) => {
        return value == item.id;
      });
      if (bol) {
        this.$message({
          type: "error",
          message: "输入序号与现有序号冲突，请重新输入！",
        });
        this.form.id = "";
      }
    },
    async getList() {
      const res = await screenList({
        page: this.page,
        pageSize: this.pageSize,
      });
      if (res.code == 0) {
        this.total = res.data.total;
        this.tableData = res.data.list;
      }
    },
    handleAvatarSuccess(res, file) {
      this.form.dialogImageUrl = URL.createObjectURL(file.raw);
    },
    //覆盖默认的上传行为，自定义上传的实现
    async upLoad(file) {
      await ossToken({
        type: 0,
      }).then((res) => {
        if (res.code == 0) {
          this.dataObj = {
            accessKeyId: res.data.accessKey,
            accessKeySecret: res.data.accessSecret,
            securityToken: res.data.token,
            region: "oss-cn-hangzhou",
            bucket: res.data.bucket,
          };
        }
      });
      const self = this;
      let files = file.file,
        point = files.name.lastIndexOf("."),
        suffix = files.name.substr(point),
        fileName = files.name.substr(0, point),
        date = Date.parse(new Date()),
        // fileNames = "/img/" + file.file.name;
        fileNames =
          "/img/" +
          Math.round(new Date() / 1000) +
          "." +
          file.file.name.substring(file.file.name.lastIndexOf(".") + 1);
      console.log(fileNames);
      // console.log(file.file.name.substring(file.file.name.lastIndexOf(".")+1));
      //fileNames上传文件的名称
      //file.file上传文件的内容
      client(this.dataObj)
        .multipartUpload(fileNames, file.file)
        .then((result) => {
          this.form.resource = fileNames;
          //下面是如果对返回结果再进行处理，根据项目需要
          self.$message({
            message: "上传成功",
            type: "success",
          });
        })
        .catch((err) => {
          self.$message.error("上传失败");
        });
    },
    handlePictureCardPreview(file) {
      console.log(1);
      this.form.dialogImageUrl = file.url;
    },
    submit() {
      // this.dialogVisible = false
      this.$refs.form.validate(async (valid) => {
        // console.log(valid);
        if (valid) {
          const res = await screenAdd(this.form);
          if (res.code == 0) {
            this.$message({
              type: "success",
              message: "添加成功！",
            });
            this.getList();
            this.dialogVisible = false;
          }
        }
      });
    },
    close() {
      this.$refs.form.resetFields();
      this.form.dialogImageUrl = "";
    },
    async upOrDown(id, status) {
      // console.log(obj);
      const res = await screenSetScreenStatus({ id, status });
      if (res.code == 0) {
        this.$message({
          type: "success",
          message: "操作成功！",
        });
        this.getList();
      }
    },
  },
  created() {
    this.getList();
  },
};
</script>

<style lang="less" scoped>
.firstScreen {
  padding: 20px;
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409eff;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 80px;
    height: 80px;
    line-height: 80px;
    text-align: center;
  }
  .avatar {
    width: 80px;
    height: 80px;
    display: block;
  }
  .el-icon-plus {
    display: inline-block;
    width: 250px;
    line-height: 400px;
    height: 400px;
    border: 1px dashed #ccc;
  }
  .img {
    border: 1px dashed #ccc;
  }
}
</style>